package main

import (
    "fmt"
    "net/http"
    "strings"
    "io/ioutil"
    "regexp"
    "encoding/json"
    "./tv"
)

const host = "http://tv.com/"

func tvSearchHandler (w http.ResponseWriter, r *http.Request) {
    showName := strings.Replace( r.URL.Path[ len("/tv/search/"): ], " ", "+", -1 )
    data, err := retrieveData(host + "search?q=" + showName)

    if err != nil {
        http.Error(w, "{message:\"No Content\"}", 204)
    } else {
        showEpisodesData, err := retrieveData( extractTvShowLink(data) )
        if err != nil {
            http.Error(w, "{message:\"No Content\"}", 204)
        }  else {
            show := tv.NewShow(showEpisodesData)
            if len(show.Seasons) > 0 {
                b, _ := json.Marshal(show)
                fmt.Fprintf(w, "%s", b)
            } else {
                http.Error(w, "{message:\"No Content\"}", 204)
            }
        }
    }
}

func retrieveData (url string) (data string, err error) {
    response, exception := http.Get(url)
    if exception != nil {
        err = exception
    } else {
        defer response.Body.Close()
        contents, exception := ioutil.ReadAll(response.Body)
        if exception != nil {
            err = exception
        } else {
            data = string(contents)
        }
    }
    return
}

func extractTvShowLink (html string) (tvLink string) {
    showLinkRegex, _ := regexp.Compile("shows/[-0-9A-Za-z]+/")
    tvLink = host + showLinkRegex.FindString(html) + "/episodes/?printable=1"
    return
}

func main() {
    http.HandleFunc("/tv/search/", tvSearchHandler)
    http.ListenAndServe(":8080", nil)
}
